package com.quanshu.exchange.ui.gui.message.chat.row;

import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baselibrary.util.glide.GlideUtils;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.exceptions.HyphenateException;
import com.hyphenate.util.DateUtils;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.chat.ChatConstant;
import com.quanshu.exchange.support.db.UserDao;
import com.quanshu.exchange.support.entity.UserEntity;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.DateUtil;
import com.quanshu.exchange.support.utils.LogUtil;
import com.quanshu.exchange.ui.base.MyApplication;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

/**
 * Created by jye on 2018/1/20.
 */
public class BaseChatRowViewHolder extends RecyclerView.ViewHolder {

    public TextView date;              // 日期
    public TextView userName;          // 用户名
    public ImageView avatar;           // 头像
    public RelativeLayout bubble;      // 气泡
    public ImageButton replyBtn;       // 回复按钮
    public TextView replyContent;      // 回复对象
    public LinearLayout progressView;  // 发送消息中
    public ImageButton statView;      // 发送消息状态
    public EMMessage chatMessage;      // 消息
    public EMMessage preMessage;       // 上一个消息（可能没有）
    public RxAppCompatActivity context;       // 上下文
    public String groupOwner;          // 群主ID
    public UserEntity currentUser;     // 当前用户

    public BaseChatRowViewHolder(Context context, View view) {
        super(view);
        this.context = (RxAppCompatActivity) context;
        currentUser = MyApplication.getInstance().getCurrentUser();
        date = view.findViewById(R.id.chat_timestamp);
        userName = view.findViewById(R.id.chat_user_name);
        avatar = view.findViewById(R.id.chat_avatar);
        bubble = view.findViewById(R.id.chat_bubble);
        replyBtn = view.findViewById(R.id.chat_reply_btn);
        progressView = view.findViewById(R.id.chat_progress_view);
        statView = view.findViewById(R.id.chat_msg_state);
        replyContent = view.findViewById(R.id.chat_content_reply);
    }

    public void setViewInfo(EMMessage chatMessage, EMMessage preMessage, String groupOwner) {
        this.chatMessage = chatMessage;
        this.preMessage = preMessage;
        this.groupOwner = groupOwner;
        if (chatMessage != null) {
            if (date != null) {
                //设置日期
                if (preMessage == null) {
                    date.setText(DateUtil.Time2Date(chatMessage.getMsgTime() + "", "MM-dd HH:mm"));
                    date.setVisibility(View.VISIBLE);
                } else {
                    // show time stamp if interval with last message is > 30 seconds
                    if (preMessage != null && DateUtils.isCloseEnough(chatMessage.getMsgTime(), preMessage.getMsgTime())) {
                        date.setVisibility(View.GONE);
                    } else {
                        date.setText(DateUtil.Time2Date(chatMessage.getMsgTime() + "", "MM-dd HH:mm"));
                        date.setVisibility(View.VISIBLE);
                    }
                }
            }
            // 如果是发送信息
            if (chatMessage.direct() == EMMessage.Direct.SEND) {
                if (!chatMessage.getFrom().equals("admin")) {
                    UserEntity currentUser = MyApplication.getInstance().getCurrentUser();
                    GlideUtils.setRoundImageView(context, currentUser.getAvatar(), R.drawable.default_avatar, avatar);
                }
                setSendCallBack();
                String reply;
                try {
                    reply = chatMessage.getStringAttribute(ChatConstant.Chat_reply_member);
                    if (reply != null && reply.trim().length() > 0) {
                        UserEntity userEntity = UserDao.getInstance().query(reply);
                        // 先从数据库中查找
                        if (userEntity != null) {
                            if (replyContent != null) {
                                replyContent.setVisibility(View.VISIBLE);
                                replyContent.setText("回复: " + AppUtils.getUserName(userEntity));
                            }
                        } else {
                            if (replyContent != null) {
                                replyContent.setVisibility(View.VISIBLE);
                                replyContent.setText("回复: " + reply);
                            }
                        }
                    } else {
                        if (replyContent != null) {
                            replyContent.setVisibility(View.GONE);
                        }
                    }
                } catch (HyphenateException e) {
                    e.printStackTrace();
                    if (replyContent != null) {
                        replyContent.setVisibility(View.GONE);
                    }
                }
                String orginalSrc;
                try {
                    orginalSrc = chatMessage.getStringAttribute(ChatConstant.Chat_orginal_src);
                    if (orginalSrc != null && orginalSrc.trim().length() > 0) {
                        UserEntity userEntity = UserDao.getInstance().query(orginalSrc);
                        // 先从数据库中查找
                        if (userEntity != null) {
                            if (replyContent != null) {
                                replyContent.setVisibility(View.VISIBLE);
                                replyContent.setText("来自: " + AppUtils.getUserName(userEntity));
                            }
                        } else {
                            if (replyContent != null) {
                                replyContent.setVisibility(View.VISIBLE);
                                replyContent.setText("来自: " + orginalSrc);
                            }
                        }
                    }
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
            }
            // 如果是接收信息
            else {
                //设置头像
                String fromAvatar = "";
                try {
                    fromAvatar = chatMessage.getStringAttribute(ChatConstant.Chat_ext_attr_photo);
                } catch (HyphenateException e) {
                    e.printStackTrace();
                } finally {
                    if (avatar != null) {
                        GlideUtils.setRoundImageView(context, fromAvatar, R.drawable.default_avatar, avatar);
                    }
                }
                // 设置回复按钮显示不显示
                String from = chatMessage.getFrom();
                if (from.equals("admin")) {
                    if (replyBtn != null) {
                        replyBtn.setVisibility(View.GONE);
                    }
                } else {
                    // 如果是群主
                    if (groupOwner != null && groupOwner.equals(currentUser.getMemberid())) {
                        if (replyBtn != null) {
                            replyBtn.setVisibility(View.VISIBLE);
                        }
                    } else {
                        if (replyBtn != null) {
                            replyBtn.setVisibility(View.GONE);
                        }
                    }
                }
                if (chatMessage.getChatType() == EMMessage.ChatType.GroupChat) {
                    //设置用户名
                    UserEntity userEntity = UserDao.getInstance().query(from);
                    // 先从数据库中查找
                    if (userEntity != null) {
                        if (userName != null) {
                            userName.setVisibility(View.VISIBLE);
                            userName.setText(AppUtils.getUserName(userEntity));
                        }
                    } else {
                        String nickname;
                        try {
                            nickname = chatMessage.getStringAttribute(ChatConstant.Chat_ext_attr_nickname);
                            if (nickname != null && nickname.length() > 0) {
                                if (userName != null) {
                                    userName.setVisibility(View.VISIBLE);
                                    userName.setText(nickname);
                                }
                            } else {
                                if (userName != null) {
                                    userName.setVisibility(View.VISIBLE);
                                    userName.setText(from);
                                }
                            }
                        } catch (HyphenateException e) {
                            e.printStackTrace();
                            if (userName != null) {
                                userName.setVisibility(View.GONE);
                            }
                        }
                    }
                } else {
                    if (userName != null) {
                        userName.setVisibility(View.GONE);
                    }
                }
            }
        }
    }

    private void setSendCallBack() {
        EMMessage.Status status = chatMessage.status();
        LogUtil.print("====msgID==3=====" + chatMessage.getMsgId());
        context.runOnUiThread(() -> setSendStatus());
        if (status == EMMessage.Status.SUCCESS || status == EMMessage.Status.FAIL) {
            return;
        }
        chatMessage.setMessageStatusCallback(new EMCallBack() {
            @Override
            public void onSuccess() {

                context.runOnUiThread(() -> {
                    LogUtil.print("====msgID==3=callback==onSuccess==" + chatMessage.getMsgId());
                    setSendStatus();
                });
            }

            @Override
            public void onError(int code, String error) {
                context.runOnUiThread(() -> {
                    LogUtil.print("====msgID==3=callback==onError==" + code);
                    LogUtil.print("====msgID==3=callback==onError==" + error);
                    LogUtil.print("====msgID==3=callback==onError==" + chatMessage.getMsgId());
                    setSendStatus();
                });
            }

            @Override
            public void onProgress(int progress, String status) {
                context.runOnUiThread(() -> {
                    LogUtil.print("====msgID==3=callback==onProgress==" + chatMessage.getMsgId());
                    setSendStatus();
                });
            }
        });
        // Already in progress, do not send again
        if (status == EMMessage.Status.INPROGRESS) {
            return;
        }
        // Send the message
        LogUtil.print("====msgID==4==" + chatMessage.getMsgId());
        EMClient.getInstance().chatManager().sendMessage(chatMessage);
    }

    protected void setSendStatus() {
        switch (chatMessage.status()) {
            case CREATE:
                onMessageCreate();
                break;
            case SUCCESS:
                onMessageSuccess();
                break;
            case FAIL:
                onMessageError();
                break;
            case INPROGRESS:
                onMessageInProgress();
                break;
        }
    }

    private void onMessageCreate() {
        if (progressView != null) {
            progressView.setVisibility(View.VISIBLE);
        }
        if (statView != null) {
            statView.setVisibility(View.GONE);
        }
    }

    private void onMessageSuccess() {
        if (progressView != null) {
            progressView.setVisibility(View.GONE);
        }
        if (statView != null) {
            statView.setVisibility(View.GONE);
        }
    }

    private void onMessageError() {
        if (progressView != null) {
            progressView.setVisibility(View.GONE);
        }
        if (statView != null) {
            statView.setVisibility(View.VISIBLE);
        }
    }

    private void onMessageInProgress() {
        if (progressView != null) {
            progressView.setVisibility(View.VISIBLE);
        }
        if (statView != null) {
            statView.setVisibility(View.GONE);
        }
    }


    public void asyncDownloadVoice(final EMMessage message) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                EMClient.getInstance().chatManager().downloadAttachment(message);
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
            }
        }.execute();
    }

}
